package com.ymt.bpm.dingtalk.service;

import com.alibaba.fastjson.JSONObject;
import com.ymt.bpm.appboot.BpmpProperties;
import com.ymt.bpm.dao.MDao;
import com.ymt.bpm.dao.Mapper;
import com.ymt.bpm.model.PTenant;
import com.ymt.bpm.model.PTenantDdMapp;
import com.ymt.bpm.util.AES;
import com.ymt.bpm.util.Const;
import com.ymt.bpm.util.DateUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;

@Service
@EnableConfigurationProperties(value = {BpmpProperties.class})
public class DDMAppMgmService {

    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private MDao dao;

    @Autowired
    private BpmpProperties properties;

    public JSONObject getDefault(String tenantId, String loginName, String displayName) {
        PTenantDdMapp mapp = dao.selectOne(Mapper.PTenantDdMappMapper, "selectDefaultAppByTenantId", tenantId);
        if (mapp==null) {
            //初始化一个默认的
            mapp = new PTenantDdMapp();
            if (tenantId!=null && StringUtils.isNumeric(tenantId)) {
                mapp.setTenantId(Integer.parseInt(tenantId));
            }
            mapp.setCreator(loginName);
            mapp.setCreatorName(displayName);
            mapp.setCreateTime(DateUtil.getGMTDate());
            dao.insert(Mapper.PTenantDdMappMapper, "insertSelective", mapp);
        }
        JSONObject rtn = (JSONObject) JSONObject.toJSON(mapp);
        rtn.put("homeUrl", properties.getSiteUrl() + "/pages/mobile/dd/index?a=" + AES.encrypt(String.valueOf(mapp.getDdAppId())));
        return rtn;
    }

    public JSONObject save(String mappStr) {
        JSONObject jo = JSONObject.parseObject(mappStr);
        PTenantDdMapp mapp = jo.toJavaObject(PTenantDdMapp.class);
        JSONObject rtn = new JSONObject();
        int rs = dao.update(Mapper.PTenantDdMappMapper, "updateByPrimaryKeySelective", mapp);
        rtn.put(Const.AJAX_RESULT, rs);
        return rtn;
    }

}
